package netWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:Tcp协议回显服务端
 * User: 王圆豪
 * Date: 2025-05-16
 * Time: 14:28
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true) {
            Socket socketClient = serverSocket.accept();

            executorService.submit(()->{
                try {
                    processConnection(socketClient);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

//            //通过手动new Thread对象实现多客户端连接
//            Thread t = new Thread(()->{
//                processConnection(socketClient);
//            });
//            t.start();
        }
    }

    private void processConnection(Socket socketClient) throws IOException {
        System.out.printf("[%s:%d] 客户端已上线!\n",socketClient.getInetAddress(),
                socketClient.getPort());
        try (InputStream inputStream = socketClient.getInputStream();
            OutputStream outputStream = socketClient.getOutputStream()){
            Scanner sc = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                if (!sc.hasNext()) {
                    System.out.printf("[%s:%d] 客户端已下线!\n",socketClient.getInetAddress(),
                            socketClient.getPort());
                    break;
                }
                String request = sc.next();
                String reponse = process(request);
                writer.println(reponse);
                writer.flush();
                System.out.printf("[%s:%d] req: %s, rep: %s\n", socketClient.getInetAddress(),
                        socketClient.getPort(),request,reponse);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            socketClient.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
